//
//  GPSearchContanctController.m
//  Keping
//
//  Created by 23 on 2017/12/10.
//  Copyright © 2017年 柯平. All rights reserved.
//

#import "GPSearchContanctController.h"
#import "CMSearchBar.h"
#import "GPContactCell.h"
#import "KSOSRequest.h"
#import "KSosListModel.h"
#import "GPContactModel.h"
#import "GPFriendRequestController.h"
#import "GPChatController.h"

@interface GPSearchContanctController () <UITextFieldDelegate>

/**搜索框*/
@property(nonatomic,weak) CMSearchBar *searchView;

/**datas*/
@property(nonatomic,strong) NSMutableArray *datas;

@end

@implementation GPSearchContanctController

static NSString * const Id = @"search";

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    [self.view endEditing:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.leftBarButtonItem = nil;
    self.navigationItem.hidesBackButton = YES;
    
    CMSearchBar * searchView = [[CMSearchBar alloc]init];
    searchView.backgroundColor = [UIColor whiteColor];
    searchView.layer.masksToBounds=YES;
    searchView.textColor=[UIColor blackColor];
    searchView.returnKeyType = UIReturnKeySearch;
    searchView.enablesReturnKeyAutomatically = YES;
    searchView.placeholder= @"Phone/Nickname";
    searchView.frame = CGRectMake(0, 0, self.view.width - 100, 38);
    searchView.delegate = self;
    self.navigationItem.titleView = searchView;

    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Cancel" style:UIBarButtonItemStyleDone target:self action:@selector(cancel)];
    
    
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass(GPContactCell.class) bundle:nil] forCellReuseIdentifier:Id];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.refreshEnable = NO;
    self.tableView.loadmoreEnable = NO;
    
}

- (void)viewWillLayoutSubviews
{
    [super viewWillLayoutSubviews];
    
    self.searchView.layer.cornerRadius = 0.5 * 38;
    self.searchView.layer.masksToBounds = YES;
}


#pragma mark - UITableViewDelegate UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.datas.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    WEAKSELF
    GPContactCell *cell = [tableView dequeueReusableCellWithIdentifier:Id];
    cell.type = GPContactCellTypeSearchContact;
    cell.contact = self.datas[indexPath.row];
    cell.callback = ^(GPContactModel *contactModel) {
      
        //添加好友
        GPFriendRequestController *vc = [[GPFriendRequestController alloc] init];
        vc.friendId = contactModel.partyId;
        vc.nickname = contactModel.nickName;
        [weakSelf.navigationController pushViewController:vc animated:YES];

        
    };
    
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    GPContactModel *contact = self.datas[indexPath.row];
    if (contact.status == 2) {
        //是好友，跳转到好友聊天室
        GPChatViewModel *chatViewModel = [[GPChatViewModel alloc] initWithChatType:EMChatTypeChat conversationId:contact.phone toId:contact.phone toNickName:contact.nickName toAvatarURLPath:[KGetImageURL stringByAppendingPathComponent:contact.profile]];
        chatViewModel.uid = contact.partyId;
        GPChatController *vc = [[GPChatController alloc] init];
        vc.chatViewModel = chatViewModel;
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 75.f;
}


#pragma mark - action
//取消
- (void)cancel
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - UITextFieldDelegate
//点击搜索
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    //获取key
    NSString *key = textField.text;
    
    //发起搜索请求
    [self showLoading];
    KSOSRequest *searchRequest =  [[KSOSRequest alloc] initWithURL:kSosSearchFriendsURL];
    searchRequest.params = @{@"searchContent":key};
    [searchRequest startWithCompletionBlockWithSuccess:^(__kindof KBaseRequest * _Nonnull request) {
        
        [self hideHUD];
        NSDictionary *response = request.responseJSONObject;
        if ([response[@"statusCode"] integerValue] != 200) {
            
            [self showErrorText:response[@"msg"] errCode:[response[@"statusCode"] integerValue]];
            return;
        }
        
        NSMutableArray *arrayM = [NSMutableArray array];
        for (NSDictionary *dict in response[@"relationFriendViews"]) {
            KSosListModel *model = [KSosListModel modelWithDictionary:dict];
            GPContactModel *contact = [self contactModelWithListModel:model];
            [arrayM addObject:contact];
        }
        
        self.datas = [NSMutableArray arrayWithArray:arrayM];
        [self.tableView reloadData];
        
        
    } failure:^(__kindof KBaseRequest * _Nonnull request) {
        [self hideHUD];
        [self showError:request.error];
    }];
    
    return YES;
}


- (GPContactModel *)contactModelWithListModel:(KSosListModel *)listModel
{
    GPContactModel *contactModel = [[GPContactModel alloc] init];
    
    contactModel.nickName = listModel.nickName;
    contactModel.partyId  = listModel.friendId;
    contactModel.phone    = listModel.phone;
    contactModel.profile  = listModel.profile;
    contactModel.status   = listModel.status;
    contactModel.context  = listModel;
    
    return contactModel;
}

#pragma mark - lazy
- (NSMutableArray *)datas
{
    if (_datas == nil) {
        _datas = [NSMutableArray array];
    }
    return _datas;
}


@end
